package com.mlm.mlmapp.activity;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.activity.layoutmanager.SyGridLayoutManager;
import com.mlm.mlmapp.adapter.view.AQProgressDialog;
import com.mlm.mlmapp.adapter.view.GridMarginDecoration;
import com.mlm.mlmapp.animation.RecyclAnimation;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.DimensionRes;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@EActivity(R.layout.combo_list)
public class ComboListActivity extends BaseActivity implements HTTPCons {
    public static final int REQUEST_CODE = 11;
    @DimensionRes(R.dimen.recyclerview_mycomments_space)
    float commentImagesMargin;
    @DimensionRes
    float comments_images_edge;
    @ColorRes
    int lred;
    @ColorRes
    int blacktext;
    public String currentJson = "";
    @ViewById
    TextView tv_no_title;
    private AQuery aq;
    private ComboListAdapter adapter;
    List<JSONObject> comboListDataset;
    @ViewById
    RecyclerView rv_combos;
    @Extra
    String comboid;
    @Extra
    String id;

    @AfterViews
    public void init() {
        String title = getTitle().toString();
        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        aq.hardwareAccelerated11();
        comboListDataset = new ArrayList<>();
        HashMap<String, String> map = new HashMap<>();

        map.put("levelId",comboid);
        aq.progress(new AQProgressDialog(this)).ajax(CommonUtils.getURLStringParams(get_combos_action, map),
//		aq.ajax(get_combos_action,
                JSONArray.class,
                new AjaxCallback<JSONArray>() {

                    @Override
                    public void callback(String url, JSONArray array,
                                         AjaxStatus status) {
                        if (status.getCode() == -101) {
                            Toast.makeText(aq.getContext(),
                                    "网络异常,请检查网络", Toast.LENGTH_SHORT);
                            return;
                        }
                        // TODO Auto-generated method stub
                        if (status.getCode() != 200) {
                            Toast.makeText(aq.getContext(),
                                    "网络异常:" + status.getCode(),
                                    Toast.LENGTH_SHORT).show();
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj;
                                try {
                                    obj = array.getJSONObject(i);
                                    comboListDataset.add(obj);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                            }
                            adapter.notifyDataSetChanged();

                        }
                    }

                });

        final GridLayoutManager layoutManager = new SyGridLayoutManager(this, 1);
        rv_combos.setLayoutManager(layoutManager);
        rv_combos.addItemDecoration(new GridMarginDecoration(this, 0, 0, 0,
                commentImagesMargin));
        rv_combos.setItemAnimator(new RecyclAnimation());
        adapter = new ComboListAdapter(ComboListActivity.this, comboListDataset);
        rv_combos.setAdapter(adapter);
    }

    class ComboListAdapter extends
            RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private Context mContext;
        private List<JSONObject> array;
        private List<RadioButton> rlist;

        public ComboListAdapter(Context con, List<JSONObject> array) {
            this.mContext = con;
            this.array = array;
            rlist = new ArrayList<RadioButton>();
        }

        @Override
        public int getItemCount() {
            return array.size();
        }

        public boolean isPositionHeader(int position) {
            return position == 0;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                          int viewType) {
            // TODO Auto-generated method stub

            final ComboViewHolder holder = new ComboViewHolder(LayoutInflater
                    .from(ComboListActivity.this).inflate(
                            R.layout.combo_list_item, parent, false));
            return holder;

        }

        private void radioGroupChecked(CompoundButton buttonView) {
            for (RadioButton rb : rlist) {
                if ((int) rb.getTag() != (int) buttonView.getTag()) {
                    rb.setChecked(false);
                }

            }
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder,
                                     int position) {
            // TODO Auto-generated method stub
            final ComboViewHolder vholder = (ComboViewHolder) holder;
            final JSONObject json = array.get(position);
            vholder.radio_combo.setText(getJsonString(json, "names"));
            vholder.radio_combo.setTag(position);
            rlist.add(vholder.radio_combo);
            vholder.radio_combo
                    .setOnCheckedChangeListener(new OnCheckedChangeListener() {

                        @Override
                        public void onCheckedChanged(CompoundButton buttonView,
                                                     boolean isChecked) {
                            // TODO Auto-generated method stub
                            if (isChecked) {
                                radioGroupChecked(buttonView);
                                currentJson = json.toString();
                                vholder.radio_combo.setTextColor(lred);
                                vholder.btn_price.setTextColor(lred);
                            } else {
                                vholder.radio_combo.setTextColor(blacktext);
                                vholder.btn_price.setTextColor(blacktext);
                            }
                        }
                    });
            if (getJsonString(json, "id").equals(comboid))
                vholder.radio_combo.setChecked(true);
            vholder.btn_price.setText(getString(R.string.money,
                    getJsonInt(json, "comboValues")));
            JSONArray list = getJsonArray(json, "comboDetails");
            vholder.ll_group.removeAllViews();
            if (list.length() > 0) {
                for (int i = 0; i < list.length(); i++) {
                    try {
                        JSONObject obj = list.getJSONObject(i).getJSONObject(
                                "productInfo");
                        String name = getJsonString(obj, "productName");

                        View v = LayoutInflater
                                .from(ComboListActivity.this)
                                .inflate(R.layout.combo_group_item, null, false);
                        TextView tvname = (TextView) v
                                .findViewById(R.id.row_group_item);
                        tvname.setText(name);
                        vholder.ll_group.addView(v);
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }

            }

        }

        public class ComboViewHolder extends RecyclerView.ViewHolder {
            Button btn_price;
            RadioButton radio_combo;
            LinearLayout ll_group;

            public ComboViewHolder(View itemView) {
                super(itemView);
                this.btn_price = (Button) itemView.findViewById(R.id.btn_price);
                this.radio_combo = (RadioButton) itemView
                        .findViewById(R.id.radio_combo);
                this.ll_group = (LinearLayout) itemView
                        .findViewById(R.id.ll_group);
            }
        }
    }

    @Click
    void btn_confirm() {
        if ("".equals(currentJson)) {
            Toast.makeText(aq.getContext(), "请先选择您需要的套餐", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Intent data = new Intent();
            data.putExtra("jsonString", currentJson);
            setResult(RESULT_OK, data);
            this.finish();

        }
    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
        Intent data = new Intent();
        setResult(RESULT_CANCELED, data);
        this.finish();
    }

}
